package com.thd.springboottest.security.securitycustom;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thd.springboottest.security.entity.User;
import com.thd.springboottest.security.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义登录成功后的处理器
 **/
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功后的处理");
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        System.out.println("登录用户：" + userDetails.getUsername());

        ObjectMapper json = new ObjectMapper();
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        // 生成jwtToken
        User u = (User)authentication.getPrincipal();
        Map<String,Object> claims = new HashMap<String,Object>();
        claims.put("mobile",u.getPhone());
        claims.put("username",u.getUsername());
        String jwtToken = JwtTokenUtil.getInstance().generateToken(userDetails.getUsername(),claims);




//        httpServletResponse.getWriter().write(json.writeValueAsString(authentication));
        httpServletResponse.getWriter().write(jwtToken);

    }
}
